package com.ewili.framework.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;

public class HttpClientUtils {

    /**
     * 获取链接内容
     *
     * @param url
     * @return
     */
    public static String getContent(String url, int connectTimeout, int socketTimeout) {
        String content = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
        HttpGet get = new HttpGet(url);
        get.setConfig(config);
        try {
            CloseableHttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            content = EntityUtils.toString(entity, "utf-8");
            response.close();
            httpClient.close();
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }
        return content;
    }

    public static String getContent(String url, int timeout) {
        Connection connection = Jsoup.connect(url);
        connection.maxBodySize(0);
        connection.timeout(timeout);
        try {
            return connection.get().body().text();
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }
        return null;
    }

    public static String getContentByJsoup(String url,String jsonKey) {
        Connection conn = Jsoup.connect(url).timeout(10000000).ignoreContentType(true);
        String content = "";
        try {
            content = conn.get().toString();
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }

        if (!StringUtils.contains(content, jsonKey)) {
            return null;
        }
        return content;
    }
}
